package com.tim.app.ui.activity.selected;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.KeyboardChangeListener;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.callback.ReplyCallback;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Answer;
import com.tim.app.server.entry.Comment;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.ActionResult;
import com.tim.app.server.result.AnswerDetailResult;
import com.tim.app.server.result.AnswerListResult;
import com.tim.app.server.result.CollectResult;
import com.tim.app.server.result.CommentResult;
import com.tim.app.server.result.PublishCommentResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.share.CustomShareBoard;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.EmptyActivity;
import com.tim.app.ui.activity.SearchActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.ui.adapter.comment.CommentInfoAdapter;
import com.tim.app.ui.view.AnswerHeadView;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 回答详情页面
 */
public class AnswerDetailActivity extends BaseActivity implements LoadMoreHandler, KeyboardChangeListener.KeyBoardListener {

    public static final String TAG = "AnswerDetailActivity";
    private Answer answer;
    private boolean isFromPush = false;

    private ImageButton ibBack;
    private ImageButton ibMore;
    private LinearLayout llAgree;
    private ImageView ivAgree;
    private TextView tvAgreeNumber;
    private LinearLayout llOpposition;
    private ImageView ivOpposition;
    private TextView tvOppositionNumber;
    private LinearLayout llCollect;
    private ImageView ivCollect;
    private TextView tvCollect;
    private LinearLayout llComment;
    private TextView tvCommentNumber;

    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvComment;

    private CommentInfoAdapter adapter;
    private List<Comment> commentList;

    private LinearLayout llCommentContainer;
    private TextView tvComment;
    private View icInput;

    private KeyboardChangeListener mKeyboardChangeListener;

    private View vTopView;
    private TextView tvPostComment;
    private EditText etInputComment;
    private TextView tvNextAnswer;

    private AnswerHeadView answerHeadView;
    EmptyLayout emptyLayout;
    LinearLayoutManager layoutManager;

    Handler mHandler;
    AgreeTask agreeTask;
    OppositionTask oppositionTask;

    public static void start(Context context, Answer answer, boolean isFromPush) {
        Intent intent = new Intent(context, AnswerDetailActivity.class);
        intent.putExtra(AppKey.ANSWER, answer);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_answer_detail;
    }

    StringResponseCallback detailCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                AnswerDetailResult result = new Gson().fromJson(resultValue, AnswerDetailResult.class);
                if (null != result && null != result.getRes() && null != result.getRes().getAnswer()) {
                    answer = result.getRes().getAnswer();
                    answerHeadView.showContent(answer.getContentUrl());
                    updateUi(answer);
                    wrvComment.scrollToPosition(0);
                }
            } else if (errCode == ResponseResult.ResultStatus.DELETED) {
                emptyLayout.showEmpty();
                EmptyActivity.start(AnswerDetailActivity.this);
                finish();
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    @Override
    public void initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ibMore = (ImageButton) findViewById(R.id.ibMore);
        llAgree = (LinearLayout) findViewById(R.id.llAgree);
        ivAgree = (ImageView) findViewById(R.id.ivAgree);
        tvAgreeNumber = (TextView) findViewById(R.id.tvAgreeNumber);

        llOpposition = (LinearLayout) findViewById(R.id.llOpposition);
        ivOpposition = (ImageView) findViewById(R.id.ivOpposition);
        tvOppositionNumber = (TextView) findViewById(R.id.tvOppositionNumber);

        ivCollect = (ImageView) findViewById(R.id.ivCollect);
        tvCollect = (TextView) findViewById(R.id.tvCollect);
        tvCommentNumber = (TextView) findViewById(R.id.tvCommentNumber);

        llCommentContainer = (LinearLayout) findViewById(R.id.llCommentContainer);
        tvComment = (TextView) findViewById(R.id.tvComment);

        llCollect = (LinearLayout) findViewById(R.id.llCollect);
        llComment = (LinearLayout) findViewById(R.id.llComment);

        tvNextAnswer = (TextView) findViewById(R.id.tvNextAnswer);

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvComment = (WrapRecyclerView) findViewById(R.id.wrvComment);
        wrvComment.setOverScrollMode(View.OVER_SCROLL_NEVER);

        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_search);
        emptyLayout.setEmptyText("该内容已经被删除了", "");

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

        ibMore.setOnClickListener(this);
        ibBack.setOnClickListener(this);
        llComment.setOnClickListener(this);
        llCollect.setOnClickListener(this);
        llOpposition.setOnClickListener(this);
        llAgree.setOnClickListener(this);
        tvComment.setOnClickListener(this);

        answerHeadView = (AnswerHeadView) LayoutInflater.from(this).inflate(R.layout.answer_head_view, null);

        icInput = findViewById(R.id.icInput);
        vTopView = findViewById(R.id.vTopView);
        tvPostComment = (TextView) findViewById(R.id.tvPostComment);
        etInputComment = (EditText) findViewById(R.id.etInputComment);

        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvComment.setLayoutManager(layoutManager);

        answer = (Answer) getIntent().getSerializableExtra(AppKey.ANSWER);
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);

        commentList = new ArrayList<>();
        adapter = new CommentInfoAdapter(this, commentList, AppKey.TYPE_ANSWER, answer.getId());
        wrvComment.setAdapter(adapter);
        wrvComment.addHeaderView(answerHeadView);

        wrvComment.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy < 0) {
                    llCommentContainer.setVisibility(View.GONE);
                }
            }
        });

        wrvComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isShowKeyboard) {
                    SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
                    return true;
                } else {
                    return false;
                }
            }
        });
        vTopView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
                return true;
            }
        });

        etInputComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(etInputComment.getText().toString())) {
                    tvPostComment.setEnabled(true);
                } else {
                    tvPostComment.setEnabled(false);
                }
            }
        });

        tvPostComment.setOnClickListener(this);

        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);

        tvNextAnswer.setOnClickListener(this);
        API_Statistics.ins().addDetailData(TAG, this, AppKey.TYPE_ANSWER, answer.getId());
        updateUi(answer);

        mHandler = new Handler();
        agreeTask = new AgreeTask();
        oppositionTask = new OppositionTask();

        EventManager.ins().registListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().registListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().registListener(EventTag.DO_AGREE, eventListener);
        EventManager.ins().registListener(EventTag.DO_EDIT_ANSWER, eventListener);
        EventManager.ins().registListener(EventTag.DO_OPPOSITION, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().registListener(EventTag.ON_ANSWER_EDIT, eventListener);
        EventManager.ins().registListener(EventTag.ON_COMMENT_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_SELECT_PEPLY, eventListener);
    }

    private void updateUi(Answer answer) {
        if (null == answer) {
            return;
        }
        answerHeadView.setData(answer);
        tvAgreeNumber.setText(getString(R.string.answerPriseNumber, String.valueOf(answer.getAgreeCount())));
        tvOppositionNumber.setText(getString(R.string.answerOppositionNumber, String.valueOf(answer.getOpposeCount())));
        tvCommentNumber.setText(getString(R.string.commentNumber, String.valueOf(answer.getCommentCount())));
        if (null != answer.getActionStateMsg()) {
            if (null != answer.getActionStateMsg().getAgreeState()) {
                ivAgree.setSelected(true);
                ivOpposition.setSelected(false);
                isAgree = true;
                initAgree = true;
            } else if (null != answer.getActionStateMsg().getOpposeState()) {
                ivOpposition.setSelected(true);
                ivAgree.setSelected(false);
                isOppose = false;
                initOppose = true;
            } else {
                ivAgree.setSelected(false);
                ivOpposition.setSelected(false);
            }

            if (null != answer.getActionStateMsg().getCollentState()) {
                tvCollect.setText(R.string.hasCollect);
                ivCollect.setSelected(true);
            } else {
                tvCollect.setText(R.string.unCollect);
                ivCollect.setSelected(false);
            }
        } else {
            ivAgree.setSelected(false);
            ivOpposition.setSelected(false);
            tvCollect.setText(R.string.unCollect);
            ivCollect.setSelected(false);
        }
    }

    private void updatePriseImage() {
        if (null != answer.getActionStateMsg()) {
            if (null != answer.getActionStateMsg().getAgreeState()) {
                ivAgree.setSelected(true);
                ivOpposition.setSelected(false);
                isAgree = true;
            } else if (null != answer.getActionStateMsg().getOpposeState()) {
                ivOpposition.setSelected(true);
                ivAgree.setSelected(false);
                isOppose = true;
            } else {
                ivAgree.setSelected(false);
                ivOpposition.setSelected(false);
            }
            tvAgreeNumber.setText(getString(R.string.answerPriseNumber, String.valueOf(answer.getAgreeCount())));
            tvOppositionNumber.setText(getString(R.string.answerOppositionNumber, String.valueOf(answer.getOpposeCount())));
        }
    }

    @Override
    public void initData() {
        API_Found.ins().getAnswerDetailInfo(TAG, String.valueOf(answer.getId()), detailCallback);
        API_Found.ins().getCommentList(TAG, AppKey.NO_SORT, AppKey.TYPE_ANSWER, answer.getId(), pageNumber, AppKey.PAGE_SIZE, refreshCallback);
        UserManager.ins().addBrowserHistory(TAG, AppKey.TYPE_ANSWER, answer.getId());
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.ibMore:
                SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
                CustomShareBoard shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.ANSWER);
                if (UserManager.ins().isLogin() && !TextUtils.isEmpty(answer.getUserId())) {
                    if (answer.getUserId().equals(UserManager.ins().getUserId())) {
                        shareBoard.setDelete(true);
                        shareBoard.setEidt(true, true);
                    }
                }
                String targetUrl = answer.getShareUrl();
                String imageUrl = ServerAddressManager.SHARE_DEFAULT_LOGO_URL;
                String title = answer.getProblemTitle() + " - " + answer.getUserMsg().getName() + "的回答";
                String sinaDesc = title + "  " + answer.getShareUrl() + " (解答情感问题，下载@茉莉社区 APP)";
                if (null != answer.getImageUrl() && answer.getImageUrl().size() > 0) {
                    imageUrl = answer.getImageUrl().get(0);
                }
                shareBoard.setShareInfo(title, answer.getDigest(), sinaDesc, imageUrl, imageUrl, targetUrl);
                shareBoard.showPopup(false);
                break;
            case R.id.llAgree:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                if (null != answer.getUserMsg() && !TextUtils.isEmpty(answer.getUserMsg().getUserId()) && answer.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                    ToastUtil.showToast("不能对自己的回答进行点赞");
                    return;
                }
                isAgree = !isAgree;
                if (isAgree) {
                    ivAgree.setSelected(true);
                    ivOpposition.setSelected(false);
                    answer.setAgreeCount(answer.getAgreeCount() + 1);
                    if (initOppose) {
                        answer.setOpposeCount(answer.getOpposeCount() - 1);
                    }
                } else {
                    ivAgree.setSelected(false);
                    answer.setAgreeCount(answer.getAgreeCount() - 1);
                }
                tvAgreeNumber.setText(getString(R.string.answerPriseNumber, String.valueOf(answer.getAgreeCount())));
                tvOppositionNumber.setText(getString(R.string.answerOppositionNumber, String.valueOf(answer.getOpposeCount())));

                mHandler.removeCallbacks(agreeTask);
                mHandler.postDelayed(agreeTask, AppKey.CLICK_REPEAT_TIME);
                break;
            case R.id.llOpposition:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                if (null != answer.getUserMsg() && !TextUtils.isEmpty(answer.getUserMsg().getUserId()) && answer.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                    ToastUtil.showToast("不能对自己的回答进行反对");
                    return;
                }
                isOppose = !isOppose;
                if (isOppose) {
                    ivAgree.setSelected(false);
                    ivOpposition.setSelected(true);
                    answer.setOpposeCount(answer.getOpposeCount() + 1);
                    if (initAgree) {
                        answer.setAgreeCount(answer.getAgreeCount() - 1);
                    }
                } else {
                    answer.setOpposeCount(answer.getOpposeCount() - 1);
                    ivOpposition.setSelected(false);
                }
                tvAgreeNumber.setText(getString(R.string.answerPriseNumber, String.valueOf(answer.getAgreeCount())));
                tvOppositionNumber.setText(getString(R.string.answerOppositionNumber, String.valueOf(answer.getOpposeCount())));
                mHandler.removeCallbacks(oppositionTask);
                mHandler.postDelayed(oppositionTask, AppKey.CLICK_REPEAT_TIME);
                break;
            case R.id.llComment:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                llCommentContainer.setVisibility(View.VISIBLE);
                break;
            case R.id.llCollect:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                collectOrCancelCollect();
                break;
            case R.id.etSearch:
                SearchActivity.start(this, SearchActivity.SEARCH_ALL, "");
                break;
            case R.id.tvProblemTitle:
                if (null != answer && !TextUtils.isEmpty(answer.getProblemId())) {
                    Problem problem = new Problem();
                    problem.setId(answer.getProblemId());
                    problem.setTitle(answer.getProblemTitle());
                    QuestionAndAnswerDetailActivity.start(this, problem, false);
                }
                break;
            case R.id.rivAvatar:
            case R.id.tvUserName:
                SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
                SomeoneHomepageActivity.start(this, answer.getUserMsg(), false);
                break;
            case R.id.tvPostComment:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                if (isReply) {
                    adapter.postReplyComment(etInputComment.getText().toString(), new ReplyCallback() {
                        @Override
                        public void onSuccess() {
                            answer.setCommentCount(answer.getCommentCount() + 1);
                            tvCommentNumber.setText(getString(R.string.commentNumber, String.valueOf(answer.getCommentCount())));
                            etInputComment.setText("");
                            etInputComment.setHint(getString(R.string.commentPrompt));
                            SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
                        }

                        @Override
                        public void onFail() {
                            ToastUtil.showToast("发布失败，请稍后再试");
                        }
                    });
                } else {
                    postComment(etInputComment.getText().toString());
                }
                break;
            case R.id.tvComment:
                moveToPosition(1);
                etInputComment.requestFocus();
                SoftKeyboardUtil.showSoftKeyboard(etInputComment);
                break;
            case R.id.tvNextAnswer:
                getNextAnswer();
                break;
        }
    }

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            wrvComment.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = wrvComment.getChildAt(n - firstItem).getTop();
            wrvComment.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            wrvComment.scrollToPosition(n);
            //这里这个变量是用在RecyclerView滚动监听里面的
        }

    }

    private int currentAnswerIndex = 1;


    /**
     * 赞同任务
     */
    class AgreeTask implements Runnable {

        @Override
        public void run() {
            if (initAgree != isAgree) {
                agree();
            }
        }
    }

    /**
     * 赞同
     */
    private void agree() {
        API_User.ins().addPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_ANSWER, answer.getId(), AppKey.AGREE, answer.getUserMsg().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ActionResult result = new Gson().fromJson(resultValue, ActionResult.class);
                    if (null != result && null != result.getRes()) {
                        if (null == answer.getActionStateMsg()) {
                            answer.setActionStateMsg(new ActionStateMsg());
                        }
                        answer.getActionStateMsg().setAgreeState(result.getRes().getAction().getId());
                    }
                }
                return false;
            }
        });
    }

    /**
     * 反对任务
     */
    class OppositionTask implements Runnable {

        @Override
        public void run() {
            if (initOppose != isOppose) {
                opposition();
            }
        }
    }

    /**
     * 反对
     */
    private void opposition() {
        API_User.ins().addPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_ANSWER, answer.getId(), AppKey.OPPOSE, answer.getUserMsg().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ActionResult result = new Gson().fromJson(resultValue, ActionResult.class);
                    if (null != result && null != result.getRes()) {
                        if (null == answer.getActionStateMsg()) {
                            answer.setActionStateMsg(new ActionStateMsg());
                        }
                        answer.getActionStateMsg().setAgreeState(result.getRes().getAction().getId());
                    }
                }
                return false;
            }
        });
    }

    /**
     * 获取下一个回答
     */
    private void getNextAnswer() {
        showLoadingDialog();
        API_Found.ins().getNextAnswer(TAG, answer.getId(), answer.getProblemId(), false, currentAnswerIndex, 1, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    AnswerListResult result = new Gson().fromJson(resultValue, AnswerListResult.class);

                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        if (null != result.getRes().getArraylist().getResult()) {
                            answer = result.getRes().getArraylist().getResult().get(0);
                            currentAnswerIndex++;
                            initData();
                        } else {
                            ToastUtil.showToast("没有更多回答了");
                        }
                    } else {
                        ToastUtil.showToast("没有更多回答了");
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
        if (isFromPush) {
            ViewGT.gotoMainActivity(AnswerDetailActivity.this);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 发表评论
     *
     * @param commmentContent
     */
    private void postComment(final String commmentContent) {
        tvPostComment.setEnabled(false);
        API_Found.ins().publishComment(TAG, UserManager.ins().getUserId(), AppKey.TYPE_ANSWER, answer.getId(), commmentContent, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                SoftKeyboardUtil.hideSoftKeyboard(etInputComment);
                tvPostComment.setEnabled(true);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    API_Statistics.ins().addActionData(TAG, AnswerDetailActivity.this, AppKey.TYPE_COMMENT);
                    PublishCommentResult result = new Gson().fromJson(resultValue, PublishCommentResult.class);
                    etInputComment.setText("");
                    Comment comment = result.getRes().getComment();
                    comment.setUserMsg(UserManager.ins().getLoginUser());
                    if (commentList.size() > 0) {
                        commentList.add(0, comment);
                    } else {
                        commentList.add(comment);
                    }
                    adapter.notifyDataSetChanged();
                    answer.setCommentCount(answer.getCommentCount() + 1);
                    tvCommentNumber.setText(getString(R.string.commentNumber, String.valueOf(answer.getCommentCount())));
                    ToastUtil.showToast("发表成功！");
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    ToastUtil.showToast("由于对方的设置，你不能评论此回答");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    /**
     * 收藏/取消收藏
     */
    public void collectOrCancelCollect() {
        llCollect.setEnabled(false);
        if (null != answer.getActionStateMsg() && answer.getActionStateMsg().getCollentState() != null) {
            int id = answer.getActionStateMsg().getCollentState().intValue();
            API_User.ins().cancelCollect(TAG, UserManager.ins().getUserId(), AppKey.TYPE_ANSWER, answer.getId(), AppKey.FAVORITER_ID, id, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    llCollect.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        tvCollect.setText(R.string.unCollect);
                        ivCollect.setSelected(false);
                        answer.getActionStateMsg().setCollentState(null);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addCollect(TAG, UserManager.ins().getUserId(), AppKey.TYPE_ANSWER, answer.getId(), AppKey.FAVORITER_ID, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    llCollect.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        CollectResult result = new Gson().fromJson(resultValue, CollectResult.class);
                        if (null != result && null != result.getRes()) {
                            if (null == answer.getActionStateMsg()) {
                                answer.setActionStateMsg(new ActionStateMsg());
                            }
                            answer.getActionStateMsg().setCollentState(result.getRes().getCollent().getId());
                        }
                        tvCollect.setText(R.string.hasCollect);
                        ivCollect.setSelected(true);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

    private boolean initAgree = false;
    private boolean initOppose = false;
    private boolean isAgree = false;
    private boolean isOppose = false;

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_REPORT://举报
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().report(TAG, AppKey.TYPE_ANSWER, answer.getId());
                    } else {
                        ViewGT.gotoLoginActivity(AnswerDetailActivity.this);
                    }
                    break;
                case EventTag.DO_CONTENT_DELETE://删除
                    CustomShareBoard.ShareFrom shareFrom = (CustomShareBoard.ShareFrom) dataobj;
                    if (shareFrom == CustomShareBoard.ShareFrom.ANSWER) {
                        deleteMyAnswer();
                    }
                    break;
                case EventTag.DO_EDIT_ANSWER:
                    AnswerActivity.startWithEditAnswer(AnswerDetailActivity.this, answer);
                    break;
                case EventTag.DO_AGREE://赞同
                    if (!UserManager.ins().isLogin()) {
                        ViewGT.gotoLoginActivity(AnswerDetailActivity.this);
                        return;
                    }
                    break;
                case EventTag.DO_OPPOSITION://反对
                    if (!UserManager.ins().isLogin()) {
                        ViewGT.gotoLoginActivity(AnswerDetailActivity.this);
                        return;
                    }
                    break;
                case EventTag.ON_ANSWER_EDIT:
                case EventTag.ACCOUNT_UPDATE_INFO:
                    initData();
                    break;
                case EventTag.ON_COMMENT_DELETED://评论删除
                    int position = (int) dataobj;
                    if (commentList.size() > position) {
                        commentList.remove(position);
                        adapter.notifyDataSetChanged();
                        answer.setCommentCount(answer.getCommentCount() - 1);
                        tvCommentNumber.setText(getString(R.string.commentNumber, String.valueOf(answer.getCommentCount())));
                    }
                    break;
                case EventTag.ON_SELECT_PEPLY://选中回复
                    String typeId = String.valueOf(arg1);
                    Comment selectComment = (Comment) dataobj;
                    if (typeId.equals(answer.getId())) {
                        etInputComment.setHint(getString(R.string.replySomeone, selectComment.getUserMsg().getName()));
                        isReply = true;
                    }
                    etInputComment.setFocusable(true);
                    etInputComment.requestFocus();
                    SoftKeyboardUtil.showSoftKeyboard(etInputComment);
                    break;
            }

        }
    };

    boolean isReply = false;

    /**
     * 删除我的回答
     */
    private void deleteMyAnswer() {
        API_Found.ins().deleteMyAnswer(TAG, answer.getId(), answer.getProblemId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    ToastUtil.showToast("删除成功");
                    EventManager.ins().sendEvent(EventTag.ON_ANSWER_DELETED, Integer.valueOf(answer.getProblemId()), 0, answer.getId());
                    finish();
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    private int pageNumber = 1;

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getCommentList(TAG, AppKey.NO_SORT, AppKey.TYPE_ARTICLE, answer.getId(), pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentResult result = new Gson().fromJson(resultValue, CommentResult.class);

                if (null != result && null != result.getRes()) {
                    commentList.clear();
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        commentList.addAll(result.getRes().getArraylist().getResult());
                    }
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    load_more.loadMoreFinish(false, false);
                }
            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentResult result = new Gson().fromJson(resultValue, CommentResult.class);

                if (null != result && null != result.getRes()) {
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        commentList.addAll(result.getRes().getArraylist().getResult());
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                    }
                    adapter.notifyDataSetChanged();
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                } else {
                    load_more.loadMoreFinish(false, false);
                }

            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    boolean isShowKeyboard = false;

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        isShowKeyboard = isShow;
        if (isShow) {
            icInput.setVisibility(View.VISIBLE);
        } else {
            icInput.setVisibility(View.GONE);
            if (isReply) {
                isReply = false;
                adapter.setReplyComment(null, -1);
                etInputComment.setText("");
                etInputComment.setHint(getString(R.string.commentPrompt));
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().removeListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().removeListener(EventTag.DO_AGREE, eventListener);
        EventManager.ins().removeListener(EventTag.DO_OPPOSITION, eventListener);
        EventManager.ins().removeListener(EventTag.DO_EDIT_ANSWER, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().removeListener(EventTag.ON_ANSWER_EDIT, eventListener);
        EventManager.ins().removeListener(EventTag.ON_COMMENT_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_SELECT_PEPLY, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
        OkHttpUtils.getInstance().cancelTag(CommentInfoAdapter.TAG);
    }
}
